<template>
  <div ref="chart" style="width: 100%; height: 500px;"></div>
</template>

<script setup>
import { ref, watch, onMounted, onBeforeUnmount } from 'vue';
import * as echarts from 'echarts';

const props = defineProps({
  chartData: {
    type: Array,
    required: false,
    default: () => []
  }
});

const chart = ref(null);
let myChart = null;

const option = ref({
  tooltip: {
    trigger: 'item',
    formatter: '{b}: {c}个' // 显示名称、数量和占比
  },
  series: [
    {
      name: 'Nightingale Chart',
      type: 'pie',
      radius: [20, 150],
      center: ['50%', '50%'],
      roseType: 'area',
      data: props.chartData, // Initialize with prop data
      label: {
        show: true,
        formatter: '{b}:占比 ({d}%)' // 显示名称、数量和占比
      }
    }
  ]
});

const renderChart = () => {
  if (!myChart) {
    myChart = echarts.init(chart.value);
  }
  myChart.setOption(option.value);
};

// 窗口大小变化时重新渲染图表
const resizeChart = () => {
  if (myChart) {
    myChart.resize();
  }
};

// 在组件挂载时渲染图表并添加事件监听
onMounted(() => {
  renderChart();
  window.addEventListener('resize', resizeChart);
});

// 清理事件监听
onBeforeUnmount(() => {
  window.removeEventListener('resize', resizeChart);
});

// 监测 props 变化
watch(() => props.chartData, (newData) => {
  option.value.series[0].data = newData; // Update the data in the option
  renderChart(); // Re-render the chart
});
</script>

<style scoped>
/* 可以根据需要添加样式 */
</style>
